const conf = require("./conf")
const { EventEmitter } = require("events")

const { MongoClient } = require("mongodb")

class Mongodb {
  constructor(conf) {
    //保存config
    this.conf = conf
    this.emmiter = new EventEmitter()

    //连接
    this.client = new MongoClient(conf.url, {
      useNewUrlParser: true,
      useUnifiedTopology: true
    })
    this.client.connect(err => {
      if (err) throw err
      console.log("连接成功")
      this.emmiter.emit("connect")
    })
  }
  /**
   * 返回集合
   * @param {*} colName
   * @param {*} dbName
   */
  col(colName, dbName = conf.dbName) {
    return this.client.db(dbName).collection(colName)
  }

  /**
   * 订阅连接事件
   * @param {*} event
   * @param {*} cb
   */
  once(event, cb) {
    this.emmiter.once(event, cb)
  }
}

module.exports = new Mongodb(conf)
